﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Xml.Serialization;
using System.Runtime.Serialization;

namespace Skyper.Service {
	[DataContract(Name="Config",Namespace="http://skyper/")]
	public class ServiceConfig {
		#region Fields
		private static ServiceConfig instance = new ServiceConfig();
		#endregion
		#region Constructor
		private ServiceConfig() {
			this.Hostname = "localhost";
			this.Port = "6789";
			this.UseAnyIP = true;
		}
		#endregion
		#region Public
		public static void Save() {
			try {
				using (var fs = new FileStream("config.xml", FileMode.Create, FileAccess.Write, FileShare.None)) {
					var xs = new DataContractSerializer(typeof(ServiceConfig));
					
					xs.WriteObject(fs, instance);

					fs.Close();
				}
			} catch (Exception exc) {
				if (Debugger.IsAttached) {
					Debugger.Break();
				}
				Console.WriteLine(exc);
			}
		}
		public static void Load() {
			try {
				if (File.Exists("config.xml")) {
					using (var fs = new FileStream("config.xml", FileMode.Open, FileAccess.Read, FileShare.None)) {
						var xs = new DataContractSerializer(typeof(ServiceConfig));

						Object obj = xs.ReadObject(fs);

						if (obj != null) {
							ServiceConfig cfg = obj as ServiceConfig;

							if (cfg != null) {
								instance = cfg;
							}
						}
						
						fs.Close();
					}
				}
			} catch (Exception exc) {
				if (Debugger.IsAttached) {
					Debugger.Break();
				}
				Console.WriteLine(exc);
			}
		}
		#endregion
		#region Property
		[IgnoreDataMember]
		public static ServiceConfig Instance {
			get {
				return instance;
			}
		}
		[DataMember(IsRequired=true,EmitDefaultValue=true)]
		public String Hostname {
			get;
			set;
		}
		[DataMember(IsRequired = true, EmitDefaultValue = true)]
		public String Port {
			get;
			set;
		}
		[DataMember(IsRequired = true, EmitDefaultValue = true)]
		public Boolean UseAnyIP {
			get;
			set;
		}
		#endregion
	}
}
